//
//  HMSinaHomeTableViewController.swift
//  ZJCSina
//
//  Created by 朱建超 on 16/11/12.
//  Copyright © 2016年 itHeiMa. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel

private let HMSinaStatusesCellID = "HMSinaStatusesCellID"
private let HMSinaZhuanFaCellID = "HMSinaZhuanFaCellID"
let originalCell = UINib(nibName: "HMSinaStatusesCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMSinaStatusesCell

let zhuanFaCell = UINib(nibName: "HMSinaZhuanFaCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMSinaStatusesCell

class HMSinaHomeTableViewController: HMSinaBaseTableViewController {

    lazy var needLoadArray: [IndexPath] = [IndexPath]()
    
    //控制器应该拥有视图模型
    lazy var homeViewModel : HMSinaHomeViewModel = HMSinaHomeViewModel()
    
    lazy var hmRefreshController : HMSinaRefreshController = HMSinaRefreshController()
    
    //把下面的属性拿到HMSinaHomeViewModel中
//    lazy var statuses : [HMSinaStatuses] = [HMSinaStatuses]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !login {
            //用户没有登录
            loginView.upDateUI(title: "关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            
            return
        }
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(push))
        
        setupTableView()
        
            loadData()
            
        }
    
    func loadData() {
        
        //控制器只关注状态
        homeViewModel.loadData(isPull: indicator.isAnimating) { (isSuccess , count) in
        
            if !isSuccess{
            
                return
            
            }
            
            //当小菊花的动画失效的时候提示
            if self.indicator.isAnimating == false{
                
                self.startAnimation(count: count)
                
            }
            
            //刷新界面
            self.indicator.stopAnimating()
            //停止转动
//            self.refreshControl?.endRefreshing()
            self.hmRefreshController.endRefreshing()
            
            self.tableView.reloadData()
            
        }
        
//        homeViewModel.loadData { (array) in
//            
//            //记录数组
//            self.statuses = array
//            
//            //刷新界面
//            self.tableView.reloadData()
//        }
        
    }
    
    //提示显示多少条数据
    private func startAnimation(count : Int) {
        
        //如果正在执行动画，就直接返回
        if tiShiLabel.isHidden == false {
            return
        }
        
        var textCount : String?
        
        if count == 0 {
            textCount = "没有新微薄"
        }else{
        
        textCount = "有\(count)条新微薄"
        }
        
        tiShiLabel.text = textCount
        //在开始动画前显示tiShiLabel
        self.tiShiLabel.isHidden = false
        //在开始动画前记录Y值
        let tiShiLabelY = self.tiShiLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            
            self.tiShiLabel.frame.origin.y = 64
            
        }, completion: { (Bool) in
            
            //回去的动画延迟
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                
                self.tiShiLabel.frame.origin.y = tiShiLabelY
                
            }, completion: { (Bool) in
                
                self.tiShiLabel.isHidden = true
                
            })
            
        })
        
    }
    
    private func setupTableView() {
        
        //注册cell
        //没有登录的情况下，程序会奔溃。因为根视图是访客视图，tableView没有值
//        tableView.register(HMSinaStatusesCell.self, forCellReuseIdentifier: cellID)
        let statusesCellNib = UINib(nibName: "HMSinaStatusesCell", bundle: nil)
        let zhuanFaCellNib = UINib(nibName: "HMSinaZhuanFaCell", bundle: nil)
        
        tableView.register(statusesCellNib, forCellReuseIdentifier: HMSinaStatusesCellID)
        tableView.register(zhuanFaCellNib, forCellReuseIdentifier: HMSinaZhuanFaCellID)
        
        //设置行高
//        tableView.rowHeight = 360
        //取消cell的边框线
        tableView.separatorStyle = .none
        //把小菊花加入到tableView
        tableView.tableFooterView = indicator
//        //下拉刷新控件实例化
//        refreshControl = UIRefreshControl()
//        //监听事件类型
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
//        let refreshController = HMSinaRefreshController()
        
        //监听事件
        hmRefreshController.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        self.view.addSubview(hmRefreshController)
        
        //添加提示label
        tiShiLabel.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 35)
        //设置Y的初始值
        tiShiLabel.frame.origin.y = 29
        //移动至导航条下方
        self.navigationController?.view.insertSubview(tiShiLabel, belowSubview: (self.navigationController?.navigationBar)!)
        
    }
    
    //一下代码封装到HMSinaHomeViewModel中
    
//    //专门加载数据的方法，不和UI界面打交道
//    private func loadData(finished : @escaping ([HMSinaStatuses]) -> ()) {
//        
//        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        
//        let parameters = ["access_token" : HMSinaUserAccountViewModel.shared.access_token]
//        
//        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
//            
//            if error != nil{
//            
//                SVProgressHUD.showError(withStatus: "世界上最遥远的距离是没有网络")
//                return
//            
//            }
//            print(responseObject ?? 0)
//            
//            //解析数据，转换为模型
//            //需要将any？ 转换为[string:any]
//            let dict = responseObject as! [String : Any]
//            
//            //尝试转换为字典类型的数组
//            guard let array = dict["statuses"] as? [[String : Any]] else{
//            
//                return
//                
//            }
//            print(array)
//            
//            //遍历数组，字典转模型
//            var tempArray = [HMSinaStatuses]()
//            
//            for item in array {
//                
//                let statusesModel = HMSinaStatuses()
//                
//                //调用对象的yyModel中扩充的对象方法传入字典 ---> 数据模型
//                statusesModel.yy_modelSet(with: item)
//                
//                //添加到一个临时数组中
//                tempArray.append(statusesModel)
//            }
//            
//            //执行成功的回调
//            finished(tempArray)
//        }
//        
//    }
    
    @objc private func push() {
        
        let demoViewController = HMSinaDemoController()
        self.navigationController?.pushViewController(demoViewController, animated: true)
        
    }
    
    //懒加载小菊花
    lazy var indicator: UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        
        //开启小菊花的动画 , 开始执行静默加载的时候转动
//        indicator.startAnimating()
        return indicator
    }()
    
    //实例化提示加载数据的label控件
    private lazy var tiShiLabel: UILabel = {
        
        let tiShiLabel = UILabel(title: "", font: 16, textColor: UIColor.white)
        //背景颜色
        tiShiLabel.backgroundColor = UIColor.orange
        //设置影藏
        tiShiLabel.isHidden = true
        tiShiLabel.textAlignment = .center
        
        return tiShiLabel
    }()

}

extension HMSinaHomeTableViewController{

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.homeViewModel.statuses.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        //        let cell = tableView.dequeueReusableCell(withIdentifier: HMSinaStatusesCellID, for: indexPath) as! HMSinaStatusesCell
        
        let statuses = self.homeViewModel.statuses[indexPath.row]
        
        //根据model判断使用哪一个可重用标识符
        let cellID = getCellID(statusesCellViewModel: statuses)
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! HMSinaStatusesCell
        
        
        //如果需要加载的数组的数量大于0 并且 正要加载的indexPath不在按需加载的数组中 就不渲染cell
        if needLoadArray.count > 0 {
            let result = needLoadArray.contains(where: { (index) -> Bool in
                return index.row == indexPath.row && index.section == indexPath.section
            })
            if !result {
                print("^    😈😈😈😈😈😈😈打酱油😈😈😈😈😈😈")
                return cell
            }
        }
        
        //        cell.textLabel?.text = statuses.statusesCell?.text
        
        cell.statusesModel = statuses
        
        return cell
    }
    
    //如果在这里完成自定刷新控件UI的更新, 这就是强耦合(按需加载)
    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        guard let ip = tableView.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
            return
        }
        guard let cip = tableView.indexPathsForVisibleRows?.first else {
            return
        }
        
        let skipCount = 12;
        
        if labs(cip.row - ip.row) > skipCount {
            guard let temp = tableView.indexPathsForRows(in: CGRect(x: 0, y: targetContentOffset.pointee.y, width: self.view.frame.width, height: self.view.frame.height)) else {
                
                return
            }
            var arr = temp
            print(velocity.y)
            //向下滑动
            if velocity.y < 0 {
                
                let indexPath = temp.last!
                if (indexPath.row + 3 < self.homeViewModel.statuses.count) {
                    arr.append(IndexPath(row: indexPath.row + 1, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 3, section: 0))
                }
            }else{
                //向上滑动
                let indexPath = temp.first!
                if (indexPath.row > 3) {
                    arr.append(IndexPath(row: indexPath.row - 3, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 1, section: 0))
                }
            }
            needLoadArray.append(contentsOf: arr)
        }
    }
    
    //按需加载的数组移除
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("------------------scrollViewWillBeginDragging")
        needLoadArray.removeAll()
    }
    //按需加载的数组移除
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("------------------scrollViewWillBeginDragging")
        needLoadArray.removeAll()
    }
    
    //先调用自动计算行高的协议方法
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        //获取cell
        let statuses = self.homeViewModel.statuses[indexPath.row]
        
        //从缓存池中获取一个cell
        //由于tableView要显示，现调用获取行高的方法 -> 在行高的内部获取缓存的cell
//        let nibName = getNib(statusesCellViewModel: statuses)
        
        //获取一个不用显示的cell来完成行高的自动计算
//        let cell = UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMSinaStatusesCell

//        let cell = self.loadCell(statusesCellViewModel: statuses)
        
        //绑定数据
//        cell.statusesModel = statuses
        //cell是自动布局，要立即生效
        //布局的计算，会影响滑动的效率  只计算一次，以后直接返回计算好的值
        //viewModel对应的行高是一定的  在viewModel中添加行高的属性  完成行高的记录，以后就直接返回内存存储的行高
//        cell.layoutIfNeeded()
        
//        return cell.toolsBar.frame.maxY
        return statuses.rowheight
        
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        //如果显示的是最后一个cell，就开始执行静默加载
        if indexPath.row == homeViewModel.statuses.count - 3 && indicator.isAnimating == false{
            
            indicator.startAnimating()
            print("小菊花在转")
            loadData()
            
        }
        
    }
    
    /// 根据数据获取可重用标识符
    ///
    /// - Parameter viewmodel: 视图模型
    /// - Returns: 标识符
    private func getCellID(statusesCellViewModel : HMSinaStatusesCellViewModel) -> String {
        
        if statusesCellViewModel.statusesCell?.retweeted_status == nil {
            
            return HMSinaStatusesCellID
            
        }
        return HMSinaZhuanFaCellID
    }
    
//    private func loadCell(statusesCellViewModel : HMSinaStatusesCellViewModel) -> HMSinaStatusesCell {
//        
//        if statusesCellViewModel.statusesCell?.retweeted_status == nil {
//            
//            return originalCell
//            
//        }
//        return zhuanFaCell
//    }


}
